﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
using NymphsLib.CommonUtilities;
using MovieBrowser.Controller;
using MovieBrowser.Model;
using MovieBrowser.Parser;
using MovieBrowser.Util;

namespace MovieBrowser.Presentation.Forms
{
    public partial class UpdateMovieInformation : Form
    {

        private readonly IList<Movie> _movies;
        private readonly MovieBrowserController _controller;
        private IList<Movie> _update;


        public UpdateMovieInformation(IList<Movie> movies)
        {
            InitializeComponent();
            _movies = movies;
            _controller = new MovieBrowserController();
        }

        private void BackgroundWorker1DoWork(object sender, DoWorkEventArgs e)
        {


            FireText("Starting Background 1 ...");
            var count = _movies.Count;
            var i = 1;
            foreach (var rowMovie in _movies)
            {
                FireText("#" + i++ + "/" + count + " Searching " + rowMovie.Title);

                if (rowMovie.IsValidMovie)
                {
                    try
                    {
                        FireText(string.Format("Found Exact Match: ImdbId={0}, Title={1}", rowMovie.ImdbId, rowMovie.Title));
                        //var src = HttpHelper.FetchWebPage(MovieBrowserController.ImdbTitle + movie.ImdbId);

                        var movie = rowMovie;
                        var dbMovie = _controller.Db.Movies.Where(o => o.ImdbId == movie.ImdbId).FirstOrDefault();

                        if (dbMovie == null || !dbMovie.IsUpdated)
                        {
                            Movie m = _controller.CollectAndAddMovieToDb(rowMovie);
                            if (m != null)
                            {
                                _controller.UpdateMovieNode(rowMovie, m);
                            }
                        }
                        else
                        {
                            FireText("Movie: " + rowMovie.Title + " is marked as updated. Skipping.");
                        }
                        FireText(string.Format("Finished: ImdbId={0}, Title={1}", rowMovie.ImdbId, rowMovie.Title));
                    }
                    catch (Exception exception)
                    {
                        Logger.Exception(exception, 67);
                        FireText("Problem: " + exception.Message);
                    }
                }
                else
                {
                    try
                    {
                        FireText("Trying to guess...");
                        var src = HttpHelper.FetchWebPage(MovieBrowserController.ImdbSearch + HttpHelper.UrlEncode(MovieBrowserController.IgnoreWords(rowMovie.Title)));
                        var m = ImdbParserHelper.ToMovie(ImdbParser.GuessMovie(src));

                        if (m == null)
                        {
                            FireText(string.Format("Could not find {0}. Skipping...", rowMovie.Title));
                            continue;
                        }

                        var item = new ListViewItem(rowMovie.Title);
                        item.SubItems.Add(m.Title);
                        item.SubItems.Add(m.ImdbId);
                        item.SubItems.Add(m.Year + "");
                        item.SubItems.Add(rowMovie.FilePath);

                        item.Tag = rowMovie;

                        if (!string.IsNullOrEmpty(m.ImdbId))
                        {
                            FireText("I guess it is '" + m.Title + "' with ImdbId=" + m.ImdbId);
                            item.Checked = true;
                        }

                        AddItem(item);
                    }
                    catch (Exception exception)
                    {
                        Logger.Exception(exception, 94);
                        FireText("Problem getting information from imdb. Skipping...");
                    }
                }
            }
            FireText("DONE.... I am FINISHED...");
        }

        private void Button1Click(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();
        }

        private delegate void AddItemDelegate(object value);
        private void AddItem(object value)
        {
            try
            {
                if (listViewGuessItems.InvokeRequired)
                {
                    // This is a worker thread so delegate the task.
                    listViewGuessItems.Invoke(new AddItemDelegate(AddItem), value);
                }
                else
                {
                    // This is the UI thread so perform the task.
                    listViewGuessItems.Items.Add((ListViewItem)value);
                }
            }
            catch (Exception exception)
            {
                Logger.Exception(exception, 115);
            }
        }

        private delegate void FireTextDelegate(string text);
        private void FireText(string value)
        {
            try
            {
                if (textBoxLog.InvokeRequired)
                {
                    // This is a worker thread so delegate the task.
                    textBoxLog.Invoke(new FireTextDelegate(FireText), value);
                }
                else
                {
                    // This is the UI thread so perform the task.
                    textBoxLog.AppendText(value + "\r\n");
                }
            }
            catch (Exception exception)
            {
                Logger.Exception(exception, 137);
            }
        }

        private void ButtonUpdateClick(object sender, EventArgs e)
        {
            _update = new List<Movie>();
            foreach (ListViewItem item in listViewGuessItems.CheckedItems)
            {
                var movie = (Movie)item.Tag;
                movie.Title = item.SubItems[1].Text;
                movie.ImdbId = item.SubItems[2].Text;
                int year;
                int.TryParse(item.SubItems[3].Text, out year);
                movie.Year = year;
                movie.ImdbId = item.SubItems[2].Text;
                //movie.FilePath = item.SubItems[4].Text;

                if (!string.IsNullOrEmpty(movie.ImdbId))
                    _update.Add(movie);
            }
            backgroundWorker2.RunWorkerAsync();
        }

        private void BackgroundWorker2DoWork(object sender, DoWorkEventArgs e)
        {
            FireText("Starting Background 2 ...");
            var controller = new MovieBrowserController();
            int count = _update.Count;
            int i = 1;
            foreach (var movie in _update)
            {
                FireText("#" + i++ + "/" + count + " Found Exact Match: ImdbId= " + movie.ImdbId);
                //String src = HttpHelper.FetchWebPage(MovieBrowserController.ImdbTitle + movie.ImdbId);
                try
                {
                    var m = controller.CollectAndAddMovieToDb(movie);
                    if (m != null)
                        controller.UpdateMovieNode(movie, m);

                    FireText("Finished: ImdbId= " + movie.ImdbId);
                }
                catch (Exception exception)
                {
                    Logger.Exception(exception, 198);
                }

            }
            FireText("DONE.... I am FINISHED...");
        }
    }
}
